package com.thiswhyme.republish.common.utils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ResultSet工具类
 * Created by thiswhyme on 2021-03-21.
 */
public class ResultSetUtils {

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * ResultSet转list对象
     * @param rs
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> List<T> resultSetToList(ResultSet rs, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        Object obj = null;
        try {
            while (rs.next()) {
                obj = cls.newInstance();
                Field[] fields = cls.getDeclaredFields();
                for (Field fd : fields) {
                    fd.setAccessible(true);
                    fd.set(obj, rs.getObject(humpToLine(fd.getName())));
                }
                list.add((T) obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public static String humpToLine(String str){
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
